import { defineStore } from 'pinia';
import { musicLoginApi } from '@/api/music/login/login-music-api';
import { musicList } from '@/api/music/list/list-music-api';
import { CLOUDMUSIC_PHONE, CLOUDMUSIC_PASSWORD } from '@/constants/common-const';
import { MUSIC_COOKIE_TOKEN, getTokenFromCookie, saveTokenToCookie, clearAllCookies } from '@/utils/cookie-util';

export const musicUserStore = defineStore('musicUserStore', {
    // id: 'userStore', 默认信息
    state: () => ({
        id:'', // 用户id
    }),
    // Getter 完全等同于 Store 状态的计算值，计算state中的值
    getters:{},
    // 设置state中的基本信息
    actions:{ 
        async setUserInfo() {
            try {
                let musicCookie = getTokenFromCookie(MUSIC_COOKIE_TOKEN);
                //登录
                if(!musicCookie) { 
                    let params = {
                        phone:CLOUDMUSIC_PHONE,
                        md5_password: CLOUDMUSIC_PASSWORD
                    };
                    const resLogin = await musicLoginApi.login(params);
                    if(resLogin.code !== 200) throw new Error(resLogin.message);
                    saveTokenToCookie(MUSIC_COOKIE_TOKEN, resLogin.cookie, 365);
                    this.id = resLogin.account.id;
                };
                // 更新用户uid
                if(!this.id) {
                    const resStatus = await musicLoginApi.loginstatus({cookie:musicCookie});
                    if(resStatus.data.code !== 200) throw new Error(resStatus.message);
                    this.id = resStatus.data.account.id;
                };
            } catch (e) {
                console.error(e.message);
            };
        },
    }
})